package shudu;

import java.util.Arrays;

public class Shudu {

    private int[][] data;

    public Shudu(int[][] data) {
        this.data = data;
    }

    public static void main(String[] args) {
        int[][] data =
                        {{8, 0, 0, 0, 0, 0, 0, 0, 0},
                        {0, 0, 3, 6, 0, 0, 0, 0, 0},
                        {0, 7, 0, 0, 9, 0, 2, 0, 0},
                        {0, 5, 0, 0, 0, 7, 0, 0, 0},
                        {0, 0, 0, 0, 4, 5, 7, 0, 0},
                        {0, 0, 0, 1, 0, 0, 0, 3, 0},
                        {0, 0, 1, 0, 0, 0, 0, 6, 8},
                        {0, 0, 8, 5, 0, 0, 0, 1, 0},
                        {0, 9, 0, 0, 0, 0, 4, 0, 0}};
        Shudu shudu = new Shudu(data);
        shudu.calculate();
    }

    public void print(int[][] data) {
        for (int[] datum : data) {
            System.out.println(Arrays.toString(datum));
        }
    }

    public void calculate() {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                randomNo(i, j);
            }
        }
    }

    public void randomNo(int i, int j) {
        if (data[i][j] != 0) {
            return;
        } else {
            for (int k = 1; k <= 9; k++) {
                data[i][j] = k;
                if (check(i, j)) {
                    if (i == 8 && j == 8) {
                        this.print(data);
                    } else {
//                        this.print(data);
                        this.calculate();
                    }
                }
            }
        }
    }

    public boolean check(int i, int j) {
        for (int k = 0; k < 9; k++) {
            if (k != i) {
                if (data[k][j] == data[i][j]) {
                    return false;
                }
            }
        }
        for (int k = 0; k < 9; k++) {
            if (k != j) {
                if (data[i][k] == data[i][j]) {
                    return false;
                }
            }
        }
        int a = i / 3;
        int b = i / 3;
        for (int m = 0; m < 3; m++) {
            for (int n = 0; n < 3; n++) {
                if (a * 3 + m != i && b * 3 + n != j) {
                    if (data[a * 3 + m][b * 3 + n] == data[i][j]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
